package com.phiture.erp.produce.web.controller.admin.api;

import com.phiture.erp.basic.api.pojo.resp.ErpUserCustomizeConfigResp;
import com.phiture.erp.basic.api.service.ErpUserCustomizeConfigApi;
import com.phiture.erp.common.constants.ErpUserCustomizeConfigKeyConstants;
import com.phiture.erp.common.enums.ErpStockRecordBizTypeEnum;
import com.phiture.erp.produce.api.service.ErpProduceApi;
import com.phiture.erp.produce.dal.entity.ErpProductionTaskMaterialDO;
import com.phiture.erp.produce.dal.mapper.ErpProductionTaskMaterialMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class ErpProduceApiServiceImpl implements ErpProduceApi {


    private final ErpProductionTaskMaterialMapper productionTaskMaterialMapper;

    private final ErpUserCustomizeConfigApi erpUserCustomizeConfigApi;

    @Override
    public int updateIssuedQuantity(Long id, BigDecimal quantity, Integer outType) {

        ErpProductionTaskMaterialDO taskMaterial = productionTaskMaterialMapper.selectById(id);
        if (taskMaterial == null) {
            return -1;
        }

        if(ErpStockRecordBizTypeEnum.REQ_OUT.getType().equals(outType) || ErpStockRecordBizTypeEnum.BACK_FLUSH_OUT.getType().equals(outType)){
            // 检查 数据库已领数量+参数值是否大于等于物料需求数量

            // 获取用户自定义配置
            ErpUserCustomizeConfigResp erpStockOutReqCanExceed = erpUserCustomizeConfigApi.getUserCustomizeConfig(
                    ErpUserCustomizeConfigKeyConstants.ERP_STOCK_OUT_REQ_CAN_EXCEED);
            if (!"true".equals(erpStockOutReqCanExceed.getConfigValue())
                    && taskMaterial.getIssuedQuantity().add(quantity).subtract(taskMaterial.getReturnQuantity()).compareTo(taskMaterial.getPlannedQuantity()) > 0) {
                return -2;
            }

            // 更新已领用量
            taskMaterial.setIssuedQuantity(taskMaterial.getIssuedQuantity().add(quantity));
        }else{
            // 检查 数据库已领数量 - 退料数量是否大于等于0
            if(taskMaterial.getIssuedQuantity().subtract(quantity).compareTo(BigDecimal.ZERO) < 0) {
                return -2;
            }
            // 更新已退数量
            taskMaterial.setReturnQuantity(taskMaterial.getReturnQuantity().add(quantity));
        }

        return productionTaskMaterialMapper.updateById(taskMaterial);

    }
}
